<template>
  <div class="caregiver-medical">
    <div class="header">
      <h2>健康档案</h2>
      <p>查看和记录我照护的长者健康信息</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchParams.elderName"
            placeholder="搜索长者姓名"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchParams.recordType"
            placeholder="记录类型"
            clearable
            @change="handleSearch"
          >
            <el-option label="日常检查" value="日常检查" />
            <el-option label="血糖监测" value="血糖监测" />
            <el-option label="血压监测" value="血压监测" />
            <el-option label="心脏检查" value="心脏检查" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateChange"
          />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 操作按钮 -->
    <div class="action-section">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增健康记录
      </el-button>
      <el-button @click="handleExport">
        <el-icon><Download /></el-icon>
        导出数据
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="medicalRecords"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="elderName" label="长者姓名" width="120" align="center" />
        <el-table-column prop="recordType" label="记录类型" width="120" align="center" />
        <el-table-column prop="recordTime" label="记录时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.recordTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="bodyTemperature" label="体温(℃)" width="100" align="center" />
        <el-table-column prop="bloodPressure" label="血压" width="120" align="center" />
        <el-table-column prop="heartRate" label="心率" width="80" align="center" />
        <el-table-column prop="bloodSugar" label="血糖" width="80" align="center" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="长者" prop="elderId">
          <el-select
            v-model="formData.elderId"
            placeholder="选择长者"
            style="width: 100%"
            :disabled="isEdit"
          >
            <el-option
              v-for="elder in elders"
              :key="elder.elderId"
              :label="elder.name"
              :value="elder.elderId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="记录类型" prop="recordType">
          <el-select
            v-model="formData.recordType"
            placeholder="选择记录类型"
            style="width: 100%"
          >
            <el-option label="日常检查" value="日常检查" />
            <el-option label="血糖监测" value="血糖监测" />
            <el-option label="血压监测" value="血压监测" />
            <el-option label="心脏检查" value="心脏检查" />
          </el-select>
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker
            v-model="formData.recordTime"
            type="datetime"
            placeholder="选择记录时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="体温(℃)" prop="bodyTemperature">
              <el-input-number
                v-model="formData.bodyTemperature"
                :min="35"
                :max="42"
                :step="0.1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="心率" prop="heartRate">
              <el-input-number
                v-model="formData.heartRate"
                :min="40"
                :max="200"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="血压" prop="bloodPressure">
              <el-input
                v-model="formData.bloodPressure"
                placeholder="如：120/80"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="血糖" prop="bloodSugar">
              <el-input-number
                v-model="formData.bloodSugar"
                :min="2"
                :max="30"
                :step="0.1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入健康记录描述"
          />
        </el-form-item>
        <el-form-item label="诊断" prop="diagnosis">
          <el-input
            v-model="formData.diagnosis"
            type="textarea"
            :rows="2"
            placeholder="请输入诊断信息"
          />
        </el-form-item>
        <el-form-item label="治疗方案" prop="treatment">
          <el-input
            v-model="formData.treatment"
            type="textarea"
            :rows="2"
            placeholder="请输入治疗方案"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="健康记录详情"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="长者姓名">{{ currentRecord.elderName }}</el-descriptions-item>
        <el-descriptions-item label="记录类型">{{ currentRecord.recordType }}</el-descriptions-item>
        <el-descriptions-item label="记录时间">{{ formatDateTime(currentRecord.recordTime) }}</el-descriptions-item>
        <el-descriptions-item label="体温">{{ currentRecord.bodyTemperature }}℃</el-descriptions-item>
        <el-descriptions-item label="血压">{{ currentRecord.bloodPressure }}</el-descriptions-item>
        <el-descriptions-item label="心率">{{ currentRecord.heartRate }}次/分</el-descriptions-item>
        <el-descriptions-item label="血糖">{{ currentRecord.bloodSugar }}mmol/L</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ currentRecord.description }}</el-descriptions-item>
        <el-descriptions-item label="诊断" :span="2">{{ currentRecord.diagnosis }}</el-descriptions-item>
        <el-descriptions-item label="治疗方案" :span="2">{{ currentRecord.treatment }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Download
} from '@element-plus/icons-vue'
import { getCaregiverMedicalRecords, addMedicalRecord, updateMedicalRecord, deleteMedicalRecord } from '@/api/medical'
import { getMyElders } from '@/api/elder'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref()
const elders = ref([])

// 搜索参数
const searchParams = reactive({
  elderName: '',
  recordType: '',
  startTime: '',
  endTime: ''
})

const dateRange = ref([])

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  medicalId: '',
  elderId: '',
  recordType: '',
  recordTime: '',
  bodyTemperature: null,
  bloodPressure: '',
  heartRate: null,
  bloodSugar: null,
  description: '',
  diagnosis: '',
  treatment: ''
})

// 表单验证规则
const formRules = {
  elderId: [{ required: true, message: '请选择长者', trigger: 'change' }],
  recordType: [{ required: true, message: '请选择记录类型', trigger: 'change' }],
  recordTime: [{ required: true, message: '请选择记录时间', trigger: 'change' }],
  bodyTemperature: [{ required: true, message: '请输入体温', trigger: 'blur' }]
}

// 计算属性
const medicalRecords = ref([])
const currentRecord = ref({})
const isEdit = computed(() => !!formData.medicalId)
const dialogTitle = computed(() => isEdit.value ? '编辑健康记录' : '新增健康记录')

// 方法
const loadMedicalRecords = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchParams
    }
    const response = await getCaregiverMedicalRecords(params)
    medicalRecords.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载健康记录失败:', error)
    ElMessage.error('加载健康记录失败')
  } finally {
    loading.value = false
  }
}

const loadElders = async () => {
  try {
    const response = await getMyElders()
    elders.value = response.data || []
  } catch (error) {
    console.error('加载长者列表失败:', error)
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadMedicalRecords()
}

const handleReset = () => {
  Object.assign(searchParams, {
    elderName: '',
    recordType: '',
    startTime: '',
    endTime: ''
  })
  dateRange.value = []
  pagination.currentPage = 1
  loadMedicalRecords()
}

const handleDateChange = (dates) => {
  if (dates && dates.length === 2) {
    searchParams.startTime = dates[0]
    searchParams.endTime = dates[1]
  } else {
    searchParams.startTime = ''
    searchParams.endTime = ''
  }
}

const handleAdd = () => {
  Object.assign(formData, {
    medicalId: '',
    elderId: '',
    recordType: '',
    recordTime: new Date(),
    bodyTemperature: null,
    bloodPressure: '',
    heartRate: null,
    bloodSugar: null,
    description: '',
    diagnosis: '',
    treatment: ''
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(formData, {
    medicalId: row.medicalId,
    elderId: row.elderId,
    recordType: row.recordType,
    recordTime: new Date(row.recordTime),
    bodyTemperature: row.bodyTemperature,
    bloodPressure: row.bloodPressure,
    heartRate: row.heartRate,
    bloodSugar: row.bloodSugar,
    description: row.description,
    diagnosis: row.diagnosis,
    treatment: row.treatment
  })
  dialogVisible.value = true
}

const handleView = (row) => {
  currentRecord.value = { ...row }
  detailDialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除长者"${row.elderName}"的健康记录吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteMedicalRecord(row.medicalId)
    ElMessage.success('删除成功')
    loadMedicalRecords()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const submitData = {
      ...formData,
      recordTime: formData.recordTime ? new Date(formData.recordTime).toISOString() : null
    }
    
    if (isEdit.value) {
      await updateMedicalRecord(submitData)
      ElMessage.success('更新成功')
    } else {
      await addMedicalRecord(submitData)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    loadMedicalRecords()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
  } finally {
    submitting.value = false
  }
}

const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadMedicalRecords()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadMedicalRecords()
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadMedicalRecords()
  loadElders()
})
</script>

<style scoped>
.caregiver-medical {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.header p {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.action-section {
  margin-bottom: 20px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
